#!/bin/bash
# SPDX-License-Identifier: GPL-2.0-only

#  Copyright (c) 2014 Wind River Systems, Inc.

#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License version 2 as
#  published by the Free Software Foundation.

#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#  See the GNU General Public License for more details.

#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

# git config --list -f <filename>

usage()
{
cat << EOF

  kgit-feature -v -f --dump -o <file> [<directory>]

    -v: verbose
    -f: force overwrite output file
    --dump: dump the contents of <file>
    <directory>: if --dump is not specified, this is the directory
                 to process for kernel features

EOF
}

if [ -z "$1" ]; then
    usage
    exit
fi

while [ $# -gt 0 ]; do
    case "$1" in
    --o|-o) output_file=$2
	    shift
            ;;
    --dump) dump=t
	    ;;
    -v) verbose=t
            ;;
    -f) force=t
            ;;
         *) break
            ;;
    esac
    shift
done

if [ -z "$dump" ]; then
    directory=$1
    if [ ! -d "$directory" ]; then
	echo "ERROR. A valid search directory must be provided"
	exit 1
    fi

    files=`cd $directory; find . -name '*.scc' | xargs grep KFEATURE_DESCRIPTION | cut -f1 -d:`;
    
    if [ -z "files" ]; then
	echo "ERROR. No files with feature descriptions were found in $directory"
	exit 1
    fi

    if [ -f "$output_file" ] && [ -z "$force" ]; then
	echo "ERROR. output file \"$output_file\" exists and -f was not supplied"
	exit 1
    fi
    if [ -f "$output_file" ] && [ -n "$force" ]; then
	rm -f $output_file
    fi
    if [ -z "$output_file" ]; then
	output_file=default.config
    fi

    section=kernel-options
    for f in $files; do
	if [ -n "$verbose" ]; then
	    echo "Processing: $f"
	fi
	
	var=config
	value=`echo $f | sed 's%^./%%'`
	
	if [ -n "$verbose" ]; then
	    echo "    git config -f $output_file --add $section.$var $value"
	fi
	git config -f $output_file --add $section.$var $value
    done
fi

if [ -n "$dump" ]; then
    if [ -z "$output_file" ]; then
	output_file=default.config
    fi

    git config --list -f $output_file
fi

